<template>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>
            <a href="/">基础数据</a>
        </el-breadcrumb-item>

        <el-breadcrumb-item>管理员设置</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 搜索区域 -->
    <div style="border: 1px solid black; margin: 20px; padding: 15px;">
        <el-form :inline="true" :model="searchForm" class="demo-form-inline">
            <el-form-item label="部门名称">
                <el-input v-model="searchForm.DepartmentName" placeholder="请输入部门名称" clearable />
            </el-form-item>
            <el-form-item label="姓名">
                <el-input v-model="searchForm.Name" placeholder="请输入姓名" clearable />
            </el-form-item>
            <br>
            <el-form-item>
                <el-button type="primary" @click="getAccount">搜索</el-button>
                <el-button type="danger" @click="onSubmit">重置</el-button>
            </el-form-item>
        </el-form>
    </div>

    <div style="border: 1px solid black; margin: 20px; padding: 15px;">
        <el-button type="success" @click="AddAccount()">
            新增
        </el-button>
        <el-table :data="tableData" style="width: 100%">
            <el-table-column type="index" label="序号" width="150" />
            <el-table-column prop="name" label="账号" width="120" />
            <el-table-column prop="realName" label="真实姓名" width="120" />
            <el-table-column prop="phone" label="手机号" width="180" />
            <el-table-column prop="card" label="身份证" width="220" />
            <el-table-column prop="roleName" label="角色" width="120" />
            <el-table-column prop="departmentName" label="所属部门" width="160" />

            <el-table-column fixed="right" label="操作" min-width="120">
                <template v-slot="scope">
                    <el-button link type="primary" size="small" @click="update(scope.row)">
                        编辑
                    </el-button>
                    <el-button link type="danger" size="small" @click="del(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>

    <!-- 添加对话框 -->

    <el-dialog v-model="isOpen" title="新增管理员" width="500">

        <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto"
            class="demo-ruleForm" :size="formSize" status-icon>
            <el-form-item label="部门名称" prop="departmentIds">

                <el-cascader style="width: 500px;" :show-all-levels="false" v-model="ruleForm.departmentIds"
                    :options="trees" :props="props" />

            </el-form-item>
            <el-form-item label="姓名" prop="realName">
                <el-input v-model="ruleForm.realName" />
            </el-form-item>

            <el-form-item label="身份证号" prop="card">
                <el-input v-model="ruleForm.card" placeholder="默认后六位为登录密码" />
            </el-form-item>
            <el-form-item label="联系方式" prop="phone">
                <el-input v-model="ruleForm.phone" />
            </el-form-item>
            <el-form-item label="账号" prop="name">
                <el-input v-model="ruleForm.name" />
            </el-form-item>
            <el-form-item label="角色" prop="roleId">
                系统管理员
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="submitForm(ruleFormRef)">
                    添加
                </el-button>
                <el-button @click="resetForm(ruleFormRef)">重置</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>

    <!-- 编辑对话框 -->

    <el-dialog v-model="updateOpen" title="编辑管理员" width="500">
        {{ trees }}
        <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto"
            class="demo-ruleForm" :size="formSize" status-icon>
            <el-form-item label="部门名称">
                <!--
                options 把后端查询到的数据源绑定到级联组件上
                props 级联的属性微调
               -->
                <el-cascader style="width: 500px;" :show-all-levels="false" v-model="ruleForm.departmentId"
                    @change="cascaderchange" :options="trees" :props="props" />

                <el-cascader v-model="ruleForm.bumenId" :options="bumenTrees" :props="props" @change="handleChange" />

            </el-form-item>
            <el-form-item label="姓名" prop="realName">
                <el-input v-model="ruleForm.realName" />
            </el-form-item>

            <el-form-item label="身份证号" prop="card">
                <el-input v-model="ruleForm.card" placeholder="默认后六位为登录密码" />
            </el-form-item>
            <el-form-item label="联系方式" prop="phone">
                <el-input v-model="ruleForm.phone" />
            </el-form-item>
            <el-form-item label="账号" prop="name">
                <el-input v-model="ruleForm.name" />
            </el-form-item>
            <el-form-item label="角色" prop="roleId">
                系统管理员
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="updateForm(ruleFormRef)">
                    修改
                </el-button>
                <el-button @click="resetForm(ruleFormRef)">重置</el-button>
            </el-form-item>
        </el-form>

    </el-dialog>

</template>




<script lang="ts" setup>
import axios from 'axios';
import { onMounted, reactive, ref } from 'vue'


import { ElMessage, ElMessageBox, type ComponentSize, type FormInstance, type FormRules } from 'element-plus'
import { Row } from 'element-plus/es/components/table-v2/src/components/index.mjs';
// {
//   "name": "string",
//   "pass": "string",
//   "realName": "string",
//   "phone": "string",
//   "card": "string",
//   "roleId": 0,
//   "departmentId": 0
// }
//编辑
const updateOpen = ref(false);
const update = (row: any) => {
    console.log(row)

    updateOpen.value = true;
    ruleForm.id = row.id
    ruleForm.name = row.name
    ruleForm.pass = row.pass
    ruleForm.realName = row.realName
    ruleForm.phone = row.phone
    ruleForm.card = row.card
    ruleForm.roleId = row.roleId
    ruleForm.departmentId = row.departmentId
    ruleForm.bumenId = row.departmentId

}
const cascaderchange = (value: any) => {
    ruleForm.departmentId = value[value.length - 1]
    //把级联组件里的值进行处理,取出数组里最后一个选项的值
    //把值赋值给表单里的部门
}

//提交添加动作
const updateForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            axios.put('https://localhost:7038/api/Account/UpdateAccount', ruleForm).then(res => {
                if (res.data.data > 0) {
                    ElMessage.success(res.data.msg);
                    getAccount();
                } else {
                    ElMessage.error(res.data.msg);
                }
            });

        } else {
            console.log('error submit!', fields)
        }
    })
}


//表格中的删除
const del = (row: any) => {
    ElMessageBox.confirm(
        '您确认删除吗?',
        '警告',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            axios.put('https://localhost:7038/api/Account/DelAccount', row).then(res => {
                if (res.data.data > 0) {
                    ElMessage({
                        type: 'success',
                        message: '删除成功',
                    })
                    getAccount();
                } else {
                    ElMessage({
                        type: 'success',
                        message: '删除失敗',
                    })

                }
            });


        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消了删除',
            })
        })

}

//级联的属性
const props = ref({
    value: 'id',
    label: 'departName',
    children: 'children'
}
)
//部门级联数据源
const trees = ref([{
    value: 'guide',
    label: 'Guide',
    children: [
        {
            value: 'consistency',
            label: 'Consistency',
        }]
}])

const bumenTrees = ref([])

//选择级联之后,把数组转换为部门的id
const handleChange = (value: any) => {
    console.log(value)
    ruleForm.bumenId = value[value.length - 1]
}

//给级联数据源赋值
const setTree = () => {
    axios.get('http://localhost:5015/api/Department').then(res => {
        trees.value = res.data.data
        bumenTrees.value = res.data.data
    });
}
//定义添加时的表单
interface RuleForm {
    id: number,
    name: string
    pass: string
    realName: string
    phone: string
    card: string
    roleId: number
    departmentIds: any,
    departmentId: number,
    bumenId: number
}

const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
//添加的表单
const ruleForm = reactive<RuleForm>({
    id: 0,
    name: '',
    pass: '',
    realName: '',
    phone: '',
    card: '',
    roleId: 1,
    departmentIds: [],
    departmentId: 0,
    bumenId: 0
})


//校验规则
const rules = reactive<FormRules<RuleForm>>({
    name: [
        { required: true, message: '请输入账号', trigger: 'blur' },
        { min: 3, max: 10, message: '账号长度为3-10', trigger: 'blur' },
    ],
    realName: [
        { required: true, message: '请输入姓名', trigger: 'blur' },
        { min: 3, max: 5, message: '账号长度为3-5', trigger: 'blur' },
    ],
    card: [
        { required: true, message: '请输入身份证', trigger: 'blur' },
        { min: 18, max: 18, message: '身份证长度为18位', trigger: 'blur' },
    ],
    phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { min: 11, max: 11, message: '手机号长度为11位', trigger: 'blur' },
    ],
    departmentIds: [
        {
            type: 'array',
            required: true,
            message: '请选择部门',
            trigger: 'change',
        },
    ]
})
//提交添加动作
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            ruleForm.departmentId = ruleForm.departmentIds[ruleForm.departmentIds.length - 1]
            axios.post('https://localhost:7038/api/Account/CreateAccount', ruleForm).then(res => {
                if (res.data.data > 0) {
                    ElMessage.success("添加成功!");
                    isOpen.value = false;
                    getAccount();
                } else {

                    ElMessage.error("添加失败!");
                }
            })

        } else {
            console.log('error submit!', fields)
        }
    })
}
//重置弹窗内容
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

const options = Array.from({ length: 10000 }).map((_, idx) => ({
    value: `${idx + 1}`,
    label: `${idx + 1}`,
}))




//是否打开添加弹窗
const isOpen = ref(false)
const AddAccount = () => {

    isOpen.value = true;
}

const getAccount = () => {
    axios.defaults.headers.common["Authorization"] = "Bearer " + window.localStorage.getItem("token");
    axios.get('http://localhost:5015/api/Account/GetAccount', { params: searchForm }).then(res => {
        tableData.value = res.data.data
    })
}

const tableData = ref([{
    "name": "admin",
    "realName": "张三",
    "phone": "1",
    "card": "1",
    "roleId": 0,
    "roleName": "超级管理员",
    "departmentId": 0,
    "departmentName": "呼兰区政府"
}
])

// 搜索的表单
const searchForm = reactive({
    DepartmentName: '',
    Name: ''
})

const onSubmit = () => {
    console.log('submit!')
}

onMounted(() => {
    getAccount();
    setTree();
})


</script>

<style>
.demo-form-inline .el-input {
    --el-input-width: 220px;
}

.demo-form-inline .el-select {
    --el-select-width: 220px;
}
</style>